package com.comboo.example.web.api;

import com.comboo.example.web.exception.ErrorType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.NotNull;

/**
 * @author Sherman
 * created in 2018/12/19
 */
@JsonInclude
public class ResponseWrapper<T> {


    /**
     * 请求成功
     */
    static Integer SUCCESS_CODE = 0;

    /**
     * 请求成功
     */
    static String SUCCESS_MESSAGE = "请求成功";


    @JsonProperty(required = true)
    private Integer code;


    @NotNull
    @JsonProperty(required = true)
    private String message;

    @JsonProperty("data")
    private T payload;

    public static ResponseWrapper<Void> ok() {
        return success(null);
    }

    public static <T> ResponseWrapper<T> success(T payload) {
        ResponseWrapper<T> resp = new ResponseWrapper<>();
        resp.setCode(SUCCESS_CODE);
        resp.setMessage(SUCCESS_MESSAGE);
        resp.setPayload(payload);
        return resp;
    }

    public static ResponseWrapper<Void> error(ErrorType errorType) {
        ResponseWrapper<Void> resp = new ResponseWrapper<>();
        switch (errorType) {
            case SERVICE_ERROR:
                resp.setCode(-5);
                break;
            case UNKNOW_ERROR:
                resp.setCode(-1);
                break;
            case REQUEST_PARAM_ERROR:
                resp.setCode(-2);
                break;
            case REQUEST_PROCESS_ERROR:
                resp.setCode(-3);
                break;
            case DATA_ACCESS_ERROR:
                resp.setCode(-4);
                break;
            default:
                break;
        }
        resp.setMessage(errorType.message());
        return resp;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getPayload() {
        return payload;
    }

    public void setPayload(T payload) {
        this.payload = payload;
    }

}
